const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const webpack = require('webpack');

const devMode = process.env.NODE_ENV !== 'production'

const minimizer = [
  new UglifyJsPlugin({
    cache: true,
    parallel: true,
    sourceMap: true // set to true if you want JS source maps
  }),
  new OptimizeCSSAssetsPlugin({})
];

const commonCssLoaders = [
  MiniCssExtractPlugin.loader, // creates style nodes from JS strings or extra css
  "css-loader", // translates CSS into CommonJS
  "postcss-loader",
];

module.exports = {
  mode: devMode ? 'development' : 'production',
  devtool: devMode ? "inline-source-map" : 'hidden-source-map',
  entry: "./src/index.ts",
  output: {
    path: __dirname + '/dist',
    filename: devMode ? "bricks.development.js" : 'bricks.production.js',
    library: 'bricks',
    libraryTarget: 'umd'
  },
  optimization: {
    minimizer: devMode ? [] : minimizer
  },
  plugins: [
    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/), // 忽略moment的语言包
    new MiniCssExtractPlugin({
      // Options similar to the same options in webpackOptions.output
      // both options are optional
      filename: devMode ? "bricks.development.css" : "bricks.production.css",
      chunkFilename: "[id].css"
    })
  ],
  resolve: {
    // Add `.ts` and `.tsx` as a resolvable extension.
    extensions: [".ts", ".tsx", ".js"]
  },
  module: {
    rules: [
      // all files with a `.ts` or `.tsx` extension will be handled by `ts-loader`
      { test: /\.tsx?$/, use: [
        "babel-loader",
        "ts-loader"
      ]},
      {
        test: /\.css/,
        use: commonCssLoaders,
      },
      {
        test: /\.scss$/, use: [
          ...commonCssLoaders,
          "sass-loader", // compiles Sass to CSS
        ]
      },
      {
        test: /(\.(eot|ttf|woff|woff2)|font)$/,
        loader: 'file-loader',
        options: { outputPath: 'fonts/' }
      },
      {
        test: /\.(png|jpg|gif|svg|jpeg)$/,
        loader: 'file-loader',
        options: { outputPath: 'images/' }
      }
    ]
  },
  externals: {
    react: {
      root: 'React',
      commonjs2: 'react',
      commonjs: 'react',
      amd: 'react',
    },
    'react-dom': {
      root: 'ReactDOM',
      commonjs2: 'react-dom',
      commonjs: 'react-dom',
      amd: 'react-dom',
    },
  }
};
